//
//  RHMePriceCommonPatternVC.m
//  RuiHeApp
//
//  Created by Yan Chen on 2025/1/24.
//

#import "RHMePriceCommonPatternVC.h"
#import "RHMePricePatternCell.h"
#import "RHPatternModel.h"
#import "RHMEPricePatternDetailVC.h"

@interface RHMePriceCommonPatternVC ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic ,strong) UITableView *tableView;

@property (nonatomic ,strong) NSMutableArray *patternArr;

@property (nonatomic, assign) RequestType requestType;
//当前页数
@property (nonatomic, assign) NSInteger currentPage;
//总页数
@property (nonatomic, assign) NSInteger totalPage;
//每页多少条数据
@property (nonatomic, assign) NSInteger numOfPage;

@property (nonatomic, strong) RHPatternModel *lastPattern;
@end

@implementation RHMePriceCommonPatternVC
-(NSMutableArray *)patternArr
{
    if (!_patternArr) {
        _patternArr = [NSMutableArray array];
    }
    return _patternArr;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = CFTabViewBgColor;
    [self setupUI];
    self.requestType = RequestTypeRefresh;
    self.currentPage = 1;
    self.numOfPage = 20;
    [self getPaternList];
}

- (void)setupUI{
    kWeakSelf;
    
    QMUIButton *sureBtn = [QMUIButton buttonWithTitle:@"使用模板".rh_localized titleColor:UIColor.whiteColor titleFont:kBOLDSYSTEMFONT(20)];
    [sureBtn setCornerRadius:8];
    [sureBtn setBackgroundColor:CMainColorGreen];
    [sureBtn addTarget:self action:@selector(usePatternAction) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:sureBtn];
    [sureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_offset(15);
        make.right.mas_offset(-15);
        make.height.offset(50);
        make.bottom.mas_offset(kSafe_bottom>0?-kSafe_bottom:-15);
    }];
    
    _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    [_tableView setBackgroundColor:kCOLOR_HEX(@"#F0F5FF")];
    [_tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
    [_tableView setSeparatorColor:UIColor.clearColor];
    [_tableView setDelegate:self];
    [_tableView setDataSource:self];
    [_tableView registerClass:[RHMePricePatternCell class] forCellReuseIdentifier:@"RHMePricePatternCell"];
    _tableView.tableHeaderView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kUI_WINDOW_W, 8)];
    
    [self.view addSubview:_tableView];
   
    [_tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.mas_offset(0);
        make.bottom.equalTo(sureBtn.mas_top).offset(-15);
        make.top.mas_offset(0);
    }];

    [_tableView addHeaderRefresh:^{
        [weakSelf.tableView.mj_footer resetNoMoreData];
        weakSelf.requestType = RequestTypeRefresh;
        weakSelf.currentPage = 1;
        weakSelf.lastPattern = nil;
        [weakSelf getPaternList];
       
    }];
    
    [_tableView addBackFooterRefresh:^{
        weakSelf.requestType = RequestTypeAdd;
        weakSelf.currentPage++;
        [weakSelf getPaternList];
    }];
}

-(void)usePatternAction
{
    if (self.lastPattern) {
        if (self.usePatternBlock) {
            self.usePatternBlock(self.lastPattern);
        }
    }else{
        [QMUITips showInfo:@"请选择一个模板".rh_localized];
    }
}

-(void)getPaternList
{
    NSDictionary *para = @{@"pageNum":@(self.currentPage),
                           @"pageSize":@(self.numOfPage),
                           @"createdBy":@([PrivateMange share].currentUser.userId),
                           @"type":@(0)
    };
    [RHPatternModel startGetWithCompletionAPIKey:H_myElectricityPricePatternList argument:para requestSuccess:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
        if (resultModel.code == 200) {
            NSInteger total = [request.responseObject[@"total"] integerValue];
            self.totalPage = total%self.numOfPage? total/self.numOfPage+1 : total/self.numOfPage;
            NSMutableArray *arr = [NSMutableArray arrayWithArray:resultModel.data];
            //下拉刷新
            if(self.requestType == RequestTypeRefresh){
                [self.tableView endHeaderRefresh];
                self.patternArr = arr;
            }else{//上拉加载
                [self.tableView endFooterRefresh];
                [self.patternArr addObjectsFromArray:arr];
            }
            if(self.currentPage >= self.totalPage){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
            [self.tableView reloadData];
            if(self.patternArr.count == 0){
                [self.tableView endFooterRefreshWithNoMoreData];
            }
        }
    } requestFail:^(__kindof BaseRequest *request, ResultModel *resultModel) {
        [self.tableView endHeaderRefresh];
    }];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 10;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    return nil;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return nil;
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   
    return self.patternArr.count;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    RHMePricePatternCell *policyCell = [tableView dequeueReusableCellWithIdentifier:@"RHMePricePatternCell"];
    policyCell.selectionStyle = UITableViewCellSelectionStyleNone;
    RHPatternModel *patternModel = self.patternArr[indexPath.row];
    policyCell.patternModel =patternModel;
    policyCell.selectBlock = ^{
        if (weakSelf.lastPattern.patternId != patternModel.patternId) {
            weakSelf.lastPattern.isSelected = NO;
            weakSelf.lastPattern = patternModel;
            [weakSelf.tableView reloadData];
        }
    };
    return policyCell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    kWeakSelf;
    RHPatternModel *patternModel = self.patternArr[indexPath.row];
    RHMEPricePatternDetailVC *detailVC = [[RHMEPricePatternDetailVC alloc]init];
    detailVC.patternModel = patternModel;
    detailVC.userPatternBlock = ^(RHPatternModel * _Nonnull pattern) {
        if (weakSelf.usePatternBlock) {
            weakSelf.usePatternBlock(pattern);
        }
    };
    [self.navigationController pushViewController:detailVC animated:YES];
}

#pragma mark - JXCategoryListContentViewDelegate
/**
 实现 <JXCategoryListContentViewDelegate> 协议方法，返回该视图控制器所拥有的「视图」
 */
- (UIView *)listView {
    return self.view;
}


@end
